<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$str = file_get_contents('php://input');

if (!isset($_POST['vendor'])){
$field = json_decode($str);
print_r($field);

if(isset($field)){
$q=0;
while (next($field)){
	$q++;
}
if ($q>0)$q++;

$variabili= array();
if($q==3){
	reset($field);
for ($i=0;$i<3;$i++){
	$elemento=each($field);
	$variabili[$i]=$elemento['value'];
}
$id = $variabili[0];
$valore=$variabili[1];
echo $valore;
$campo=$variabili[2];
}
}
else{$id=$_POST['id'];$q=0;}
}
else {$q=5; $vendor=$_POST['vendor'];$l=strlen($vendor);
if(strpos($vendor, "C")){$vendor=substr($vendor,0,$l-1);$q=6;}}
echo $vendor;
include '../login/db_connect.php';
include '../login/functions.php';
sec_session_start();
if (isset ( $_COOKIE ['login_string'] )) {
	$login_string = $_COOKIE ['login_string'];
	$username = $_COOKIE ['username'];
	$user_id = $_COOKIE ['user_id'];
	
	$_SESSION ['user_id'] = $user_id;
	$_SESSION ['login_string'] = $login_string;
	$_SESSION ['username'] = $username;
}

if ((login_check ( $mysqli ) == true)&&(!empty($str))&&($q==3)){
	print_r($field);
	if($valore=="NULL")$valore='';
	$query_update="UPDATE catalog SET ".$campo."='".$valore."' WHERE product_id=".$id;
	if ($result = $mysqli->query ($query_update)) {
		$response = json_encode("update successful");
		echo $response;
	}
	
	
}
if ((login_check ( $mysqli ) == true)&&(!empty($str))&&($q==0)){
		$query_remove="DELETE FROM catalog WHERE product_id=".$id;
		if ($result = $mysqli->query ($query_remove)) {
			$response = json_encode("remove successful");
			echo $id;
		}
		
	
}
if ((login_check ( $mysqli ) == true)&&(!empty($str))&&($q==5)){
	$query_insert="INSERT INTO catalog (`product_id`, `description`, `vendor`, `units`, `price`, `initials`, `visibility`) VALUES (NULL, '', '".$vendor."', '1 --', '', '', '1')";
	if ($result = $mysqli->query ($query_insert)) {
		$response = json_encode("insert successful");
	}
	//$result->free();
	$query_max="SELECT MAX(product_id) as id FROM catalog";
	if ($result = $mysqli->query ($query_max)) {
		$row = $result->fetch_assoc ();
		$response = json_encode($row);
		echo $response;
	}
	$result->free();

}

if ((login_check ( $mysqli ) == true)&&(!empty($str))&&($q==6)){
	$query_remove_listino="DELETE FROM catalog WHERE vendor=".$vendor;
	if ($result = $mysqli->query ($query_remove_listino)) {
		$response = json_encode("listino rimosso con successo");
	}
}
?>